<script setup lang="ts">
import {ref} from "vue"
import {useRoute} from "vue-router";
import axios from "axios";
import {loginUser, ServerHost, orderStatusEnum} from "@/main";
import {downloadImg} from "@/utils";
import dayjs from 'dayjs'


import {ElMessageBox, ElNotification, FormInstance, FormRules} from "element-plus";
import vueQr from 'vue-qr/src/packages/vue-qr.vue'
import logo from "@/assets/images/logo.svg"
import {provinceData} from "@/province";
import Clipboard from "clipboard";

const route = useRoute()
const goodsId = route.params.id;
const goods = ref({
  id: "",
  name: "",
  priceCent: 0,
  img: "",
  introduction: "",
  seller_id: "",
  inventory: 0,
  sales: 0,
  add_time: "",
  type: "",
})

const goodsOrder = ref({
  id: "",
  goodsId: "",
  buyerId: "",
  buyPriceCent: 0,
  buyNum: 1,
  tel: "",
  province: "",
  city: "",
  districtAndCounty: "",
  address: "",
  receiver: "",
  buyTime: new Date(),
  shippingTime: new Date(),
  finishTime: new Date(),
  status: "",
  payMethod: "",
})

const imgUrl = ref('')
const link = ref('')
link.value = window.location.href
const isLoading = ref(true)

// 获取商品
axios.get(`${ServerHost}/getGoods?id=${goodsId}`)
    .then((res) => {
      if (res.status === 200) {
        console.log(res.data)
        goods.value = res.data
        // 更新标题
        document.title = `${goods.value.name} - 乡兴助农`;
        //  处理换行符
        goods.value.introduction = goods.value.introduction.replace(/\n/g, '<br>')
      }
      downloadImg(goods.value.img, "goodsImg/")
          .then(res => {
            if (res.status === 200) {
              const type = 'image/png'
              const blob = new Blob([res.data], {type: type})
              const imgFile = new File([blob], goods.value.img, {type: type})
              imgUrl.value = URL.createObjectURL(imgFile)
              isLoading.value = false
            }
          })
    })

let clipboard = new Clipboard("#copyLinkBtn");
const onCopyLink = () => {
  console.log(link.value)
  clipboard.on("success", function (e) {
    ElNotification({
      title: '复制成功，可以分享了',
      type: 'success',
      position: 'bottom-right',
    })
    e.clearSelection();
  })
  clipboard.on("error", function (e) {
    ElNotification({
      title: '复制失败',
      type: 'success',
      position: 'bottom-right',
    })
    e.clearSelection();
  })
}

const isPlaceAnOrderDialogVisible = ref(false)
const onClickBuyBt = () => {
  if (goodsOrder.value.buyNum <= 0) {
    ElNotification({
      title: '请输入正确的数量',
      type: 'success',
      position: 'bottom-right',
    })
    return
  } else if (goodsOrder.value.buyNum > goods.value.inventory) {
    let inventoryInsufficientMsg = '最多可采购' + goods.value.inventory + '件'
    if (goods.value.inventory <= 0)
      inventoryInsufficientMsg = '库存不足，请联系商家补货'
    ElNotification({
      title: inventoryInsufficientMsg,
      type: 'success',
      position: 'bottom-right',
    })
    return
  }
  isPlaceAnOrderDialogVisible.value = true
}

const validateNotNull = (rule: any, value: any, callback: any) => {
  if (!value) {
    let showName = "";
    switch (rule.field) {
      case "receiver":
        showName = "收货人";
        break
      case "tel":
        showName = "收货电话"
        break
      case "province":
        showName = "收货省份"
        break
      case "city":
        showName = "收货城市"
        break
      case "districtAndCounty":
        showName = "收货县区"
        break
      case "address":
        showName = "详细地址"
        break
    }
    callback(new Error(`请输入${showName}`))
  } else {
    callback()
  }
}
const validateHasItemInList = (rule: any, value: any, callback: any) => {
  console.log(rule.field)
  const itemList = eval(rule.field + "List").value
  let showName = "";
  switch (rule.field) {
    case "province":
      showName = "收货省份"
      break
    case "city":
      showName = "收货城市"
      break
    case "districtAndCounty":
      showName = "收货县区"
      break
  }
  if (!value) {
    callback(new Error(`请输入${showName}`))
  } else {
    const findItem = itemList.find((item: { value: string }) => {
      return item.value === value
    })
    if (typeof findItem === "undefined" || findItem === null) {
      callback(new Error(`请输入正确的${showName}`))
    } else {
      callback()
    }
  }
}


const goodsOrderRules = ref<FormRules<typeof goodsOrder>>({
  receiver: [{validator: validateNotNull, trigger: 'change'}],
  tel: [{validator: validateNotNull, trigger: 'change'}],
  province: [{validator: validateHasItemInList, trigger: 'change'}],
  city: [{validator: validateHasItemInList, trigger: 'change'}],
  districtAndCounty: [{validator: validateHasItemInList, trigger: 'change'}],
  address: [{validator: validateNotNull, trigger: 'change'}],
})

// 获取省份列表
const provinceList = ref([{value: ""}])
const cityList = ref([{value: ""}])
const districtAndCountyList = ref([{value: ""}])
provinceData.forEach((province: { name: "" }) => {
  provinceList.value.push({value: province.name})
})

const querySearchProvinceList = (queryString: string, cb: any) => {
  // 与输入匹配的选项
  const matchResults = provinceList.value.filter((province: { value: string }) => {
    return province.value.includes(queryString);
  })
  // 余下的选项
  const otherResults = provinceList.value.filter((province: { value: string }) => {
    return !province.value.includes(queryString);
  })
  // 与输入匹配的选项在前，余下的选项在后
  cb([...matchResults, ...otherResults])
}

const querySearchCityList = (queryString: string, cb: any) => {

  if (!goodsOrder.value.province) {
    cb([])
    return
  }

  // 寻找省份对象
  const province = provinceData.find((province: { name: string, city: { name: string } }) => {
    return province.name === goodsOrder.value.province
  })

  cityList.value = []
  province.city.forEach((city: { name: string }) => {
    cityList.value.push({value: city.name})
  })

  // 与输入匹配的选项
  const matchResults = cityList.value.filter((city: { value: string }) => {
    return city.value.includes(queryString);
  })
  // 余下的选项
  const otherResults = cityList.value.filter((city: { value: string }) => {
    return !city.value.includes(queryString);
  })
  // 与输入匹配的选项在前，余下的选项在后
  cb([...matchResults, ...otherResults])
}

const querySearchDistrictAndCountyList = (queryString: string, cb: any) => {

  if (!goodsOrder.value.city) {
    cb([])
    return
  }

  // 寻找省份对象
  const province = provinceData.find((province: { name: string, city: { name: string } }) => {
    return province.name === goodsOrder.value.province
  })

  // 寻找城市对象
  const city = province.city.find((city: { name: string }) => {
    return city.name === goodsOrder.value.city
  })

  console.log(city)

  districtAndCountyList.value = []
  city.districtAndCounty.forEach((name: string) => {
    districtAndCountyList.value.push({value: name})
  })

  console.log(districtAndCountyList.value)

  // 与输入匹配的选项
  const matchResults = districtAndCountyList.value.filter((city: { value: string }) => {
    return city.value.includes(queryString);
  })
  // 余下的选项
  const otherResults = districtAndCountyList.value.filter((city: { value: string }) => {
    return !city.value.includes(queryString);
  })
  // 与输入匹配的选项在前，余下的选项在后
  cb([...matchResults, ...otherResults])
}

const goodsOrderFormRef = ref<FormInstance>()

const onClickPlaceOrderBt = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(valid => {
    if (valid) {
      console.log('submit!')
      isPaymentDialogVisible.value = true
    } else {
      console.log('error submit!!')
    }
  })
}


const isPaymentDialogVisible = ref(false)
const paymentTagActiveName = ref('wechatPayment')
const onClickPayFinish = () => {
  goodsOrder.value.buyPriceCent = goods.value.priceCent
  goodsOrder.value.payMethod = paymentTagActiveName.value
  goodsOrder.value.buyTime = null
  goodsOrder.value.shippingTime = null
  goodsOrder.value.finishTime = null
  goodsOrder.value.buyerId = loginUser.value.id
  goodsOrder.value.goodsId = goods.value.id
  goodsOrder.value.status = orderStatusEnum["待发货"]

  axios.post(`${ServerHost}/placeAnOrder`, goodsOrder.value)
      .then((res) => {
        if (res.status === 200) {
          console.log(res.data)
          if (res.data.result === "ok") {
            ElNotification({
              title: '下单成功',
              type: 'success',
              position: 'bottom-right',
            })
            isPaymentDialogVisible.value = false
            isPlaceAnOrderDialogVisible.value = false
          } else if (res.data.result === "inventoryInsufficient") {
            ElNotification({
              title: `库存不足，当前库存为${res.data.inventory}`,
              type: 'warning',
              position: 'bottom-right',
            })
          }
        } else {
          ElNotification({
            title: '网络异常，请重试',
            type: 'error',
            position: 'bottom-right',
          })
        }
      })

  console.log(goodsOrder.value)
}

// 安卓端设备判定
const isAndroidDevice = ref(false)
const schemaUrl = `rrs://shiyue0x0.top:9902/goods?id=${goodsId}`
const userAgent = navigator.userAgent;
if (/android/i.test(userAgent)) {
  isAndroidDevice.value = true
  ElMessageBox.confirm(
      '要在“乡兴助农”APP中打开吗？',
      {
        confirmButtonText: '前往APP',
        cancelButtonText: '不需要',
        type: 'warning',
      }
  )
      .then(() => {
        launchApp()
      })
}
const launchApp = () => {
  location.href = schemaUrl
}

</script>

<template>
  <el-card class="m-2" v-loading="isLoading">
    <template #header>
      <div class="header flex  justify-center gap-2">
        <img class="cover-img" :src="imgUrl" alt="image">
        <div class="flex flex-col justify-between">
          <div class="flex flex-col gap-2">
            <p class="name">{{ goods.name }}</p>
            <p class="info"> {{ dayjs(goods.add_time).format('YYYY/MM/DD HH:mm:ss') }} · 已售
              {{ goods.sales }}</p>
            <p class="goods-item-price p-2">当前价<span
                class="goods-item-price-sign ml-2">￥</span>{{ goods.priceCent / 100 }}</p>
          </div>
          <div class="flex flex-col gap-2">
            <p class="buy-num-title">采购数量</p>
            <el-input-number class="buy-num-input" size="large" v-model="goodsOrder.buyNum" :min="0"/>
            <el-button type="primary" size="large" @click="onClickBuyBt">立即采购</el-button>
          </div>
        </div>
      </div>

    </template>

    <el-tag size="large">产品介绍</el-tag>
    <p v-html="goods.introduction"/>

    <template #footer>
      <el-button id="copyLinkBtn" @click="onCopyLink" :data-clipboard-text="link" data-clipboard-action="copy">
        复制链接
      </el-button>
      <el-popover
          placement="top-start"
      >
        <template #default>
          <vue-qr
              :text="link"
              :logoSrc="logo"
              colorDark="#33B173"/>
        </template>
        <template #reference>
          <el-button v-if="!isAndroidDevice">前往手机浏览</el-button>
        </template>
      </el-popover>
      <el-button v-if="isAndroidDevice" class="launchApp" @click="launchApp">打开APP</el-button>
    </template>
  </el-card>

  <!-- Place An Order Dialog -->
  <el-dialog
      class="placeAnOrderDialog"
      v-model="isPlaceAnOrderDialogVisible"
      title="确认订单">
    <el-form ref="goodsOrderFormRef" :rules="goodsOrderRules" :model="goodsOrder">
      <el-form-item label="收货人" prop="receiver">
        <el-input v-model="goodsOrder.receiver" placeholder="请输入收货人"></el-input>
      </el-form-item>
      <el-form-item label="收货电话" prop="tel">
        <el-input v-model="goodsOrder.tel" placeholder="请输入收货电话"></el-input>
      </el-form-item>

      <el-form-item>
        <el-form-item class="mr-4" label="收货省份" prop="province">
          <el-autocomplete v-model="goodsOrder.province" placeholder="请输入收货省份"
                           :fetch-suggestions="querySearchProvinceList">
          </el-autocomplete>
        </el-form-item>
        <el-form-item class="mr-4" label="收货城市" prop="city">
          <el-autocomplete v-model="goodsOrder.city" placeholder="请输入收货城市"
                           :fetch-suggestions="querySearchCityList">
          </el-autocomplete>
        </el-form-item>
        <el-form-item class="mr-4" label="收货县区" prop="districtAndCounty">
          <el-autocomplete v-model="goodsOrder.districtAndCounty" placeholder="请输入收货县区"
                           :fetch-suggestions="querySearchDistrictAndCountyList">
          </el-autocomplete>
        </el-form-item>
      </el-form-item>


      <el-form-item label="详细地址" prop="address">
        <el-input v-model="goodsOrder.address" placeholder="请输入详细地址"></el-input>
      </el-form-item>
      <p>共 {{ goodsOrder.buyNum }} 件，总计￥{{ goodsOrder.buyNum * goods.priceCent / 100 }}</p>
      <el-button @click="onClickPlaceOrderBt(goodsOrderFormRef)">立即下单</el-button>
    </el-form>
  </el-dialog>

  <!-- Payment Dialog -->
  <el-dialog
      v-model="isPaymentDialogVisible"
      title="提交支付"
      style="width: 400px">
    <el-tabs v-model="paymentTagActiveName" class="demo-tabs">
      <p>共 {{ goodsOrder.buyNum }} 件，总计￥{{ goodsOrder.buyNum * goods.priceCent / 100 }}</p>
      <el-tab-pane label="微信支付" name="wechatPayment"></el-tab-pane>
      <el-tab-pane label="支付宝" name="alipay"></el-tab-pane>
      <el-tab-pane label="银行卡" name="Card"></el-tab-pane>
      <div class="flex flex-col items-center">
        <vue-qr
            style="width: 200px"
            :text="link"
            :logoSrc="logo"
            colorDark="#33B173"/>
        <el-button @click="onClickPayFinish" style="width: 200px">点击完成订单</el-button>
      </div>

    </el-tabs>
  </el-dialog>
</template>

<style scoped lang="scss">
.name {
  font-size: 1.3rem;
  font-family: "思源宋体 Heavy", serif;
  color: var(--el-color-primary);
}

.info {
  font-size: 0.9rem;
  color: var(--el-color-info);
}

.cover-img {
  width: 400px;
  height: 400px;
  border-radius: 8px;
  object-fit: cover;
}

.goods-item-price {
  background-color: var(--el-color-info-light-8);
  border-radius: 4px;
}

.goods-item-price-sign {
  font-size: 0.8rem;
}

.buy-num-title {
  font-size: 0.9rem;
  color: var(--el-color-info);
}

.buy-num-input{
  width: 200px;
}
.placeAnOrderDialog{
  width: 700px
}

@media screen and (max-width: 768px) {
  .header {
    flex-direction: column;
  }
  .cover-img {
    margin: auto;
  }
  .buy-num-input{
    width: 100%;
  }

}
</style>
